package org.yak.core.provider;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


/**
 * 树结构配置缓存
 * @author xuqiang
 *
 */
public class TreeConfigCache {

	private static final Logger logger = Logger.getLogger(TreeConfigCache.class);

	//树型配置
	private static Map<String,String> treeConfig = new HashMap<String, String>();

	static{
		String path = TreeConfigCache.class.getResource("/").getPath().toString()+"conf/treeConfig.xml";
		try{
			File file = new File(path);
			SAXReader reader = new SAXReader();
			Document document = reader.read(file);
			Element root = document.getRootElement();
			@SuppressWarnings("unchecked")
			List<Element> childElements = root.elements("treeConfig");
			for (Element child : childElements) {
				String sqlKey = child.element("treeId").getText();
				String rootSql = child.element("rootSql").getText();
				//String childSql = child.element("childSql").getText();
				String mappingSql = child.element("mappingSql").getText();
				treeConfig.put(sqlKey, rootSql);
				//treeConfig.put(sqlKey+"_child", childSql);
				treeConfig.put(sqlKey+"_mapping", mappingSql);
			}
		}catch(Exception e){
			logger.error("加载配置树异常",e);
		}
	}

	/**
	 * 获取树形sql配置语句
	 * @return
	 */
	public static String getTreeConfigSql(String sqlKey){
		return treeConfig.get(sqlKey);
	}
	
	/**
	 * 树子节点语句sql
	 * @param sqlKey
	 * @return
	 */
	/*public static String getTreeConfigChildSql(String sqlKey) {
		return treeConfig.get(sqlKey+"_child");
	}*/

	/**
	 * 获取记录值映射sql
	 * @param sqlKey
	 * @return
	 */
	public static String getTreeConfigMappingSql(String sqlKey){
		return treeConfig.get(sqlKey+"_mapping");
	}

	/**
	 * 获取所有页面请求参数,将请求参数转换成treeConfig所需要的格式
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,String> getRequestTreeConfigParameterMap(HttpServletRequest request){
		Map<String,String> treeParamMap = new HashMap<String,String>();
		Map<String,String[]> pramMap = request.getParameterMap();
		for (Map.Entry<String, String[]> entry : pramMap.entrySet()) {
			//System.out.println(entry.getKey()+"--->"+entry.getValue());
			String key = "{"+entry.getKey()+"}";
			String value = request.getParameter(entry.getKey());

			treeParamMap.put(key, value);
		}
		return treeParamMap;
	}

	/**
	 * 格式化树结构查询语句，将sql中的参数替换成map中对应的参数值
	 * @param param
	 * @param treeSql,返回格式化好的sql语句
	 * @return
	 */
	public static String formatTreeSql(Map<String,String> param,String treeSql){
		if(param == null || param.isEmpty()){
			return treeSql;
		}
		for (Map.Entry<String, String> entry : param.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			//指定替换参数存在，替换成指定值
			if(treeSql.indexOf(key)>0){
				treeSql = treeSql.replace(key, "'"+value+"'");
			}
		}
		return treeSql;
	}

	/**
	 * 根据treeConfigId获取对应的树sql语句，并且自动格式化对应参数
	 * @param treeConfigId
	 * @return
	 * @throws Exception
	 */
	public static String getParseTreeSql(String treeConfigId,HttpServletRequest request) throws Exception{
		String sqlTree = getTreeConfigSql(treeConfigId);
		if(StringUtils.isEmpty(sqlTree)){
			throw new Exception("无效的树查询语句");
		}
		sqlTree = formatTreeSql(getRequestTreeConfigParameterMap(request),sqlTree);
		return sqlTree;
	}
}
